package com.lb.poitl;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.apache.poi.xwpf.usermodel.XWPFTable;

import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.deepoove.poi.util.TableTools;
import com.lb.poitl.PoiTlTest.Medicine;

/**
 * @author jzhang
 * @version 1.0
 * @date 2022/5/30 13:08
 */
public class MergeTableRenderPolicy extends LoopRowTableRenderPolicy {
    @Override
    protected void afterloop(XWPFTable table, Object data) {
        if (Objects.isNull(data))
        {
            return;
        }

        List<Medicine> list = (List<Medicine>) data;
        Map<String, List<Medicine>> nameMap = list.stream().collect(Collectors.groupingBy(Medicine::getName));

        int colIndex1 = 0;
        int colIndex5 = 5;
        int rowIndex = 1;

        for (int i = 0; i < list.size();) {
            String name = list.get(i).getName();
            List<Medicine> medicineList = nameMap.get(name);
            int count = medicineList.size();

            if (count == 1 && !(("丙戊酸".equals(medicineList.get(0).getName()) || "⽣酮饮⻝".equals(medicineList.get(0).getName())))) {
                medicineList.forEach(item -> item.setTestResultDescription(item.getMedicineAdvice()));

                TableTools.mergeCellsHorizonal(table, rowIndex, 4, 5);
            }

            if (count > 1) {
                TableTools.mergeCellsVertically(table, colIndex1, rowIndex, rowIndex + count - 1);
                TableTools.mergeCellsVertically(table, colIndex5, rowIndex, rowIndex + count - 1);
            }

            rowIndex = rowIndex + count;
            i=i+count;
        }
    }
}
